package com.rp.system.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rp.system.common.entity.Location;
import com.rp.common.utils.NullIs;
import com.rp.common.utils.Selectway;
import com.rp.system.common.mapper.LocationMapper;
import com.rp.system.common.service.LocationService;
import com.rp.system.user.mapper.SysDemoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author vicente
 * @since 2020-12-10
 */
@Service
public class LocationServiceImpl extends ServiceImpl<LocationMapper, Location> implements LocationService {

    /**
     * 位置编码上限 [A-Z]99999
     */
    final public static Integer BUILD_MAX_SIZE = 5;

    @Autowired
    private LocationMapper locationMapper;

    @Autowired
    private Selectway selectway;

    @Override
    public boolean save(Location location) {
        String parentId = location.getParentId();
        String code = "";
        char zf = 'A';
        if(parentId == null){
            Integer size = locationMapper.selectCount(new QueryWrapper<Location>().eq("length(loc_code)", BUILD_MAX_SIZE+1));
            code = zf + String.format("%0" + BUILD_MAX_SIZE + "d", size + 1);
            location.setLocName(location.getName());
            location.setLocAddress(location.getAddress());
        }else{
            Location locationParent = locationMapper.selectOne(new QueryWrapper<Location>().select("loc_name","loc_address","loc_code").eq("id", parentId));

            location.setLocName(getLocNameAndAddress(locationParent.getLocName(),location.getName()));
            location.setLocAddress(getLocNameAndAddress(locationParent.getLocAddress(),location.getAddress()));

            int codeLenth = locationParent.getLocCode().length() + BUILD_MAX_SIZE + 1;
            Integer size = locationMapper.selectCount(new QueryWrapper<Location>()
                    .eq("length(loc_code)", codeLenth)
                    .likeRight("loc_code", locationParent.getLocCode()));
            code = locationParent.getLocCode() + (char)(zf+(codeLenth/BUILD_MAX_SIZE - 1)) + String.format("%0" + BUILD_MAX_SIZE + "d", size + 1);
        }
        location.setLocCode(code);
        return super.save(location);
    }

    @Override
    public boolean updateById(Location location) {
        System.out.println(location);
        String parentId = location.getParentId();

        //修改之前的整个对象
        Location oldLocation = locationMapper.selectOne(new QueryWrapper<Location>().select("parent_id,loc_code").eq("id", location.getId()));

        if(!NullIs.isEmpty(parentId) && !parentId.equals(oldLocation.getParentId())){
            //修改了上级
            Location oldHigLocation = locationMapper.selectOne(new QueryWrapper<Location>()
                    .select("loc_name","loc_address","loc_code")
                    .eq("id", oldLocation.getParentId()));
            //现在上级  : A01B01
            Location newHigLocation = locationMapper.selectOne(new QueryWrapper<Location>().select("loc_name","loc_address","loc_code").eq("id", parentId));

            location.setLocName(getLocNameAndAddress(newHigLocation.getLocName(),location.getName()));
            location.setLocAddress(getLocNameAndAddress(newHigLocation.getLocAddress(),location.getAddress()));

            System.out.println(oldLocation.getLocCode());
            System.out.println(oldHigLocation.getLocCode());
            System.out.println(newHigLocation.getLocCode());
            //根据以前的code查询 找出 %A01B02C02_% 修改成 A01B01C02
            String now = oldLocation.getLocCode().replace(oldHigLocation.getLocCode(), newHigLocation.getLocCode());
            List<Location> locations = locationMapper.selectList(new QueryWrapper<Location>().likeRight("loc_code", oldLocation.getLocCode()));
            for(Location l : locations){
                l.setLocCode(l.getLocCode().replace(oldLocation.getLocCode(), now));
                locationMapper.updateById(l);
            }
            location.setLocCode(now);
            //查询出以前的 A01B01C02 所有  替换成   A01B02C02
        }else{
            location.setLocName(location.getName());
            location.setLocAddress(location.getAddress());
        }

        return super.updateById(location);
    }

    /**
     * @Author HuJingYu
     * @Date 17:03 2020-12-24
     * @Description 判断name不为空就加上 -Name
     * @param str1
     * @param str2
     * @return java.lang.String
     */
    private String getLocNameAndAddress(String str1,String str2){
        if(NullIs.isEmpty(str1)){
            if(NullIs.isEmpty(str2)){
                return "";
            }
            return str2;
        }else{
            if(NullIs.isEmpty(str2)){
                return str1;
            }
            return str1 + "-" + str2;
        }

    }

    @Override
    public String findlocCodeById(String id) {
        return locationMapper.findlocCodeById(id);
    }

    @Override
    public IPage<Location> page(IPage<Location> page, Wrapper<Location> queryWrapper) {
        IPage<Location> pagelist = super.page(page, queryWrapper);

//        long beginTime = System.currentTimeMillis();
//        //执行方法
//        List<Location> list = pagelist.getRecords();
//        for(Location location : list){
//            if(!NullIs.isEmpty(location.getExpand())){
//                Map<String, Object> map = JSON.parseObject(location.getExpand(), Map.class);
//                location.setExpandMap(map);
//            }
//        }
//        pagelist.setRecords(list);
//        //执行时长(毫秒)
//        long time = System.currentTimeMillis() - beginTime;
//        System.out.println("LocationServiceImpl json转换执行时长(毫秒):" + time);

        return pagelist;
    }
}
